package student

import (
	"gin-project-01/gin-step04/gin17-mutli-tables/controllers"
	myModel "gin-project-01/gin-step04/gin17-mutli-tables/models"
	"github.com/gin-gonic/gin"
	"gorm.io/gorm"
	"net/http"
	"strconv"
	"strings"
)

type LessonController struct {
	controllers.BaseController //继承 controllers.BaseController
}

// List
//
//	@Description: http://localhost:8888/lesson/list/1 | http://localhost:8888/lesson/list/0
//	@receiver a
//	@param c
func (a LessonController) List(c *gin.Context) {
	all := c.Param("all")
	if strings.EqualFold(all, "1") {
		var lessonDtoList []myModel.LessonDto
		myModel.Db.Preload("StudentList").Find(&lessonDtoList)
		c.JSON(http.StatusOK, lessonDtoList)
	} else {
		var lessonList []myModel.Lesson
		myModel.Db.Find(&lessonList)
		c.JSON(http.StatusOK, lessonList)
	}
}

// Get
//
//	@Description:  查询某个课程信息(包括选修的学生信息) http://localhost:8888/lesson/get/1
//	@receiver a
//	@param c
func (a LessonController) Get(c *gin.Context) {
	param := c.Param("id")
	id, _ := strconv.Atoi(param)
	var lesson myModel.LessonDto
	myModel.Db.Preload("StudentList").Where("id = ?", id).Find(&lesson)
	c.JSON(http.StatusOK, lesson)
}

// Exclude 查询课程信息(包括选修的学生信息,但是排除张三) http://localhost:8888/lesson/exc
func (a LessonController) Exclude(c *gin.Context) {
	var lessonList []myModel.LessonDto
	//models.Db.Preload("StudentList", "id != ?", 1).Find(&lessonList)
	myModel.Db.Preload("StudentList", "id not in ?", []int{1, 2}).Find(&lessonList)
	c.JSON(http.StatusOK, lessonList)
}

// StuDesc
//
//	@Description:  查询课程信息(包括选修的学生信息,学生id倒叙排列)  【自定义预加载SQL】 http://localhost:8888/lesson/stuDesc
//
// @receiver a
// @param c
func (a LessonController) StuDesc(c *gin.Context) {
	var lessonList []myModel.LessonDto
	myModel.Db.Preload("StudentList", func(db *gorm.DB) *gorm.DB {
		return db.Where("student.id > ?", 2).Order("student.id desc")
	}).Find(&lessonList)
	c.JSON(http.StatusOK, lessonList)
}
